package com.heying.springbootweb.restclient;

import com.heying.springbootweb.entity.Student;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class StudentRestClient {

    @Autowired
    private RestTemplate restTemplate;

    public List<Student> queryAll(){
        @SuppressWarnings("unchecked")//忽略警告
        ArrayList<Student> list = restTemplate.getForObject("http://localhost:8080/rest/stu",
                ArrayList.class);
        log.debug("list is {}",list);
        return list;
    }

    public ResponseEntity<ArrayList> queryAll2(){
        @SuppressWarnings("unchecked")
        ResponseEntity<ArrayList> responseEntity = restTemplate.getForEntity("http://localhost:8080/rest/stu",
                ArrayList.class);
        log.debug("list is {}",responseEntity.getBody());
        return responseEntity;
    }

    public Student addOne(Student stu){
        Student student = restTemplate.postForObject("http://localhost:8080/rest/stu",
                stu,Student.class);
        log.debug("student is {}",student);
        return student;
    }

    public void putOne(Student stu){
        restTemplate.put("http://localhost:8080/rest/stu/"+stu.getId(), stu);
    }

    public void patchName(Integer id,String name){
        Student stu = restTemplate.patchForObject("http://localhost:8080/rest/stu/"+id+"/"+name,
                null,Student.class);
    }

    public void delOne(Integer id){
        restTemplate.delete("http://localhost:8080/rest/stu/{id}",id);
    }
}
